package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.aliyun.openservices.ons.api.SendResult;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.util.SplitArrUtil;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Discription: 京东订单发货信息推送
 * Created with IntelliJ IDEA.
 * @Author wcy
 * @Date 2018/5/7 10:04
 */
@Component
@Slf4j
public class JingDongSendOrderService {

    @Autowired
    private SendMqServies sendMqServies;
    @Autowired
    private PropertiesConf pconf;

    @Transactional(rollbackFor = Exception.class)
    public void jingDongSendOrder(String jdSendOrderTopic, String tag, JSONObject paramObject){
        JingDongSendOrderService sendOrderService = ApplicationContextHandle.getBean(JingDongSendOrderService.class);
        //获取订单发货中间表中的订单表的外键OmsonlineOrderId并去重
         JSONArray msgArray = new JSONArray();
        String sql = "select ID,OMSONLINEORDERID,IS_SPLIT,TID,PLATFORM,SELLER_NICK,OUT_SID,COMPANY_CODE from T_OMS_OrderOutStorage where PLATFORM =4 and syncstatus=0 for update skip locked";
        JSONArray sendOrderArr = QueryEngine.getInstance().doQueryObjectArray(sql);
        if (sendOrderArr!=null && !sendOrderArr.isEmpty()){
            for (int i = 0; i < sendOrderArr.size(); i++) {


                JSONObject msgObject = new JSONObject();
                JSONObject object = sendOrderArr.getJSONObject(i);
                Long omsonlineorderid = object.getLong("OMSONLINEORDERID");
                //根据OmsonlineOrderId联查订单表获取商品表的外键ORDERSHOPID
                String orderSql = "select a.ORDERSHOPID from T_OMSONLINEORDER a inner join T_OMS_OrderOutStorage b " +
                        "on a.id=b.OMSONLINEORDERID and b.OMSONLINEORDERID=? group by a.ORDERSHOPID";
                JSONObject orderShopIdObj = QueryEngine.getInstance().doQueryObject(orderSql, new Object[]{omsonlineorderid});
                Long orderShopId = orderShopIdObj.getLong("ORDERSHOPID");
                //根据外键ORDERSHOPID联查商品表获取商品类型SHOPTYPE
                String shopTypeSql = "select SHOPTYPE from t_iesshop WHERE ID = ?";
                JSONObject shopTypeObj = QueryEngine.getInstance().doQueryObject(shopTypeSql,new Object[]{orderShopId});
                String shopType = shopTypeObj.getString("SHOPTYPE");
                msgObject.put("OMSONLINEORDERID",omsonlineorderid);
                msgObject.put("SHOPTYPE",shopType);
                int isSplit = object.getInteger("IS_SPLIT");
                Long tid = object.getLong("TID");
                msgObject.put("PLATFORM",object.getInteger("PLATFORM"));
                msgObject.put("SELLER_NICK",object.getString("SELLER_NICK"));
                msgObject.put("ID",object.getLong("ID"));
                msgObject.put("TID",tid);
                if (isSplit==0){
                    msgObject.put("IS_SPLIT",0);
                    msgObject.put("OUT_SID",object.getString("OUT_SID"));
                    msgObject.put("COMPANY_CODE",object.getString("COMPANY_CODE"));
                }
                if (isSplit==1){
                    String selectSql = "select SELLER_NICK,PLATFORM,OUT_SID,COMPANY_CODE from T_OMS_OrderOutStorage where TID=?";
                    JSONArray jsonArray = QueryEngine.getInstance().doQueryObjectArray(selectSql,new Object[]{tid});

                    StringBuffer outSid = new StringBuffer();
                    StringBuffer companyCode = new StringBuffer();
                    for (int j = 0; j < jsonArray.size(); j++) {
                        JSONObject dataObj = jsonArray.getJSONObject(j);
                        if (j == jsonArray.size() - 1) {
                            outSid.append(dataObj.getString("OUT_SID"));
                            companyCode.append(dataObj.getString("COMPANY_CODE"));
                        } else {
                            outSid.append(dataObj.getString("OUT_SID") + ",");
                            companyCode.append(dataObj.getString("COMPANY_CODE") + "|");
                        }
                    }

                    msgObject.put("IS_SPLIT",1);
                    msgObject.put("OUT_SID",outSid.toString());
                    msgObject.put("COMPANY_CODE",companyCode.toString());
                }
                msgArray.add(msgObject);
            }

            SplitArrUtil splitArrUtil = ApplicationContextHandle.getBean(SplitArrUtil.class);
            //一次发100条消息
            int count = pconf.getPropertyInt("ons.sendOrderCount");
            if (msgArray.size() > count){
                JSONArray jsonArray = splitArrUtil.splitArr(msgArray, count);
                for (Object o:jsonArray) {
                    JSONArray sendArr = JSONArray.parseArray(o.toString());
                    try {
                        //发送消息并且记录日志
                        System.out.println("发货数据===>"+sendArr.toJSONString());
                        SendResult sendResult = sendMqServies.sendMqLogRetArr(sendArr, jdSendOrderTopic, tag);
                        if (sendResult != null){
                            sendOrderService.updateStatus(sendArr);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("发送日志消息错误" + "========>");
                    }
                }
            }else {
                try {
                    SendResult sendResult = sendMqServies.sendMqLogRetArr(msgArray, jdSendOrderTopic, tag);
                    if (sendResult != null){
                        sendOrderService.updateStatus(msgArray);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("发送日志消息错误" + "========>");
                }
            }

        }else {
            log.debug("没有订单发货数据");
        }
    }

    /**
     * 获取中间表发货数据，更新syncstatus为9,表示已发送
     * */
    private void updateStatus(JSONArray jsonArray){
        JSONObject jsonObject;
        String sql = "update T_OMS_OrderOutStorage set syncstatus=9 where id = ?";
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonObject = jsonArray.getJSONObject(i);
            Long id = jsonObject.getLong("ID");
            int code = QueryEngine.getInstance().executeUpdate(sql, new Object[]{id});
            if (code <= 0){
                log.debug("id===>"+id+"更新发送状态失败");
            }
        }
    }

}
